//
//  WKHomeTableViewController.swift
//  WKWeibo
//
//  Created by 恋guang年 on 16/3/25.
//  Copyright © 2016年 恋guang年. All rights reserved.
//

import UIKit
import SVPullToRefresh

class WKHomeTableViewController: WKBaseTableViewController {
    //tableView重用标识
    private let Identifier = "Cell2"
    //属性 保存所有微博模型数组
    var statues:[WKStatus]?{
        didSet{
            //改变后 刷新数据
            self.tableView.reloadData()
        }
    }
    override func viewDidLoad() {
        if !WKUserAccountViewModel.sharedInstance.isUserLogin{
            return
        }
        super.viewDidLoad()
        
        ////       设置导航栏左右按钮
        setUpNavigationItemBarButton()
        ///  设置导航栏自定义title
        setUPNavigationTitleView()
        prepareForTableView()
     
    }
    ///设置tableveiw
    func prepareForTableView(){
        ///注册cell
        tableView.registerClass(WKStatusCell.self, forCellReuseIdentifier: Identifier)
        ///设置cell的预估行高 cell的高度根据子控件布局确定
        tableView.estimatedRowHeight = 100
        tableView.rowHeight = UITableViewAutomaticDimension
        //取消cell直接分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        //下拉加载
        tableView.addPullDownRefreshHandler { [weak self]() -> () in
            self?.loadNewStatus()
        }
        tableView.startRefreshing()
        //上拉加载
        tableView.addInfiniteScrollingWithActionHandler { [weak self] () -> Void in
            self?.loadMoreStatus()
        }
    }
    /// 加载最新的微博数据
    private func loadNewStatus() {
        
        // 获取id最大的微博, 当没有微博数据,传入0加载最新20条微博数据
        let since_id = self.statues?.first?.id ?? 0
        
        // 使用VM加载数据
        WKStatusViewModel.sharedInstance.loadStatuses(since_id, max_id: 0) { (statuses, error) -> () in
            self.tableView.endRefreshing()
            
            if error != nil {
                print("下拉刷新微博数据出错了: \(error)")
                return
            }
            
            let count = statuses?.count ?? 0
            
            if since_id > 0 {
                self.showTipLabel(count)
            }
            
            if count == 0 {
                print("没有加载到微博")
                return
            }
            
            // 下拉刷新
            if since_id > 0 {
                print("下拉刷新count: \(count)")
                // 下拉刷新,需要将新获取到的数据添加到现有数据的前面,并且重新赋值
                self.statues = statuses! + self.statues!
                
            } else { // since_id = 0
                print("第一次加载最新微博count: \(count)")
                // 加载最新20条数据
                self.statues = statuses
            }
            print( "最终微博数据条数: \(self.statues?.count)")

        }
    }
    /// 加载更多微博数据,上拉加载数据
    private func loadMoreStatus() {
        let max_id = self.statues?.last?.id ?? 0
        
        WKStatusViewModel.sharedInstance.loadStatuses(0, max_id: max_id) { (statuses, error) -> () in
            // 结束上拉加载更多数据
            self.tableView.infiniteScrollingView.stopAnimating()
            
            if error != nil {
                print("上拉加载微博数据出错了: \(error)")
                return
            }
            
            let count = statuses?.count ?? 0
            
            if count == 0 {
//                CZPrint(msg: "没有加载到微博")
                return
            }
            
            // 上拉加载更多数据,将新的数据拼接到现有数据的后面
            self.statues = self.statues! + statuses!
//            CZPrint(msg: "上拉加载更多数据: \(statuses?.count)")
//            CZPrint(msg: "最终微博数据条数: \(self.statuses?.count)")
        }
    }
    /**
     显示下拉刷新的条数
     
     - parameter count: 下拉刷新的条数
     */
    private func showTipLabel(count: Int) {
        tipLabel.text = count == 0 ? "没有新的微博数据" : "更新了\(count)条微博数据"
        
        // 动画
        UIView.animateWithDuration(0.25 * 4, animations: { () -> Void in
            self.tipLabel.frame.origin.y = 44
            }) { (_) -> Void in
                UIView.animateWithDuration(0.25 * 4, delay:0.25 * 2, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
                    self.tipLabel.frame.origin.y = -64
                    }, completion: nil)
        }
    }
    ///  设置导航栏自定义title
    private func setUPNavigationTitleView(){
        /// 获得用户昵称
        let title = WKUserAccountViewModel.sharedInstance.userAccount?.screen_name
        let titleButton = WKTitleButton(title: title, imageName: "navigationbar_arrow_down")
        navigationItem.titleView = titleButton
        titleButton.addTarget(self, action: "titleButtonDidClick:", forControlEvents: UIControlEvents.TouchUpInside)
        
    }
    ///  设置导航栏左右按钮
    private func setUpNavigationItemBarButton(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", target: self, action: "leftBarButtonItemDidClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: "rightBarButtonItemDidClick")
        
    }
    //MARK: - 按钮点击事件
    @objc private func titleButtonDidClick(button:UIButton){
        //按钮选中时箭头朝上 不是选中状态朝下
        button.selected = !button.selected
        UIView.animateWithDuration(WKDefaultDuration) { () -> Void in
            button.imageView?.transform = button.selected ? CGAffineTransformMakeRotation(CGFloat(M_PI - 0.001)) : CGAffineTransformIdentity
        }
        //如果选中状态 跳出popcover控制器
        if button.selected {
            let popCoverVC = WKPopViewController()
            popCoverVC.modalPresentationStyle = .Popover
            popCoverVC.popoverPresentationController?.sourceView = navigationItem.titleView
            popCoverVC.popoverPresentationController?.sourceRect = (navigationItem.titleView?.bounds)!
            popCoverVC.preferredContentSize = CGSize(width: 200, height: popCoverVC.titles.count*44)
            popCoverVC.popoverPresentationController?.delegate = self
            presentViewController(popCoverVC, animated: true, completion: nil)
        }
        
        
    }
    
    @objc private func leftBarButtonItemDidClick(){
        print(__FUNCTION__)
    }
    
    @objc private func rightBarButtonItemDidClick(){
        print(__FUNCTION__)
    }
    // MARK: - 懒加载
    /// 下拉刷新提示label
    private lazy var tipLabel: UILabel = {
        let tipLabel = UILabel()
        
        tipLabel.backgroundColor = UIColor.orangeColor()
        tipLabel.textColor = UIColor.whiteColor()
        tipLabel.font = UIFont.systemFontOfSize(16)
        tipLabel.textAlignment = NSTextAlignment.Center
        
        tipLabel.frame = CGRect(x: 0, y: -64, width: UIScreen.width, height: 44)
        
        // 往导航栏上面添加
        self.navigationController?.navigationBar.insertSubview(tipLabel, atIndex: 0)
        
        return tipLabel
    }()

}
//MARK: - tableView数据源和代理方法
extension WKHomeTableViewController{
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statues?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(Identifier, forIndexPath: indexPath) as! WKStatusCell
        cell.status = statues?[indexPath.row]
        return cell
    }
    
    ///取消cell的选中状态
    override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return false
    }
}
//MARK: - 扩展
extension WKHomeTableViewController:UIPopoverPresentationControllerDelegate{
    
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
        return UIModalPresentationStyle.None
    }
    
    // 系统会询问我们是否需要关闭popover
    func popoverPresentationControllerShouldDismissPopover(popoverPresentationController: UIPopoverPresentationController) -> Bool {
        // 让箭头转下来
        let titleButton = navigationItem.titleView as! WKTitleButton
        titleButtonDidClick(titleButton)
        return true
    }
}
